import { View, Button, Text, Input } from "@tarojs/components";
import { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { RoomResource } from "@/types/global";
import { useRoomService } from "../../hooks/useRoomService";

import "./index.less";

export default function Room() {
  const [roomId, setRoomId] = useState<string>('');
  const [playerIp, setPlayerIp] = useState<string>('1'); // 默认IP为1
  const [opponentIp, setOpponentIp] = useState<string | null>(null); // 对手IP，初始为空
  const [playerStatus, setPlayerStatus] = useState<{[key: string]: string}>({
    '1': '未准备'
  });
  const [isHost, setIsHost] = useState<boolean>(false);
  const [bothReady, setBothReady] = useState<boolean>(false); // 添加双方是否都准备好的状态
  const { 
    connectWebSocket, 
    addPlayerToRoom,
    sendGameCommand,
    playerReady,
    startGame,
    disconnectWebSocket, // 添加断开连接函数
    userIp,
    isConnected,
    roomResource,
    getRoomResource // 添加获取房间资源的函数
  } = useRoomService({ 
    roomId,
    onRoomResourceUpdate: handleRoomResourceUpdate,
    // 添加房间指令监听回调
    onRoomCommand: handleRoomCommand
  });

  // 页面加载时获取房间号并连接WebSocket
  useEffect(() => {
    const roomIdParam = Taro.getCurrentInstance().router?.params?.roomId;
    if (roomIdParam) {
      setRoomId(roomIdParam);
        // 初始化玩家状态
        setPlayerStatus({ [userIp]: '未准备' });
        // 连接WebSocket
        connectWebSocket(roomIdParam).then(result => {
          if (result.success) {
            console.log('WebSocket连接成功');
            // 添加玩家到房间
            addPlayerToRoom(roomIdParam).then(async response => {
              // 添加玩家成功后立即获取房间资源
              setPlayerIp(response.userIp);
              // getRoomResource(roomIdParam);
              console.log('Player IP1111:', playerIp, response.userIp);
            });
          } else {
            console.error('WebSocket连接失败:', result.error);
            Taro.showToast({ title: `连接失败: ${result.error}`, icon: 'none' });
          }
        });
    }
  }, []);

  // 处理房间资源更新
  function handleRoomResourceUpdate(resource: RoomResource) {
    console.log('房间资源更新:', resource);

    // 更新玩家状态
    const newPlayerStatus = {...playerStatus};
    
    // 检查是否有新玩家加入
    if (resource.playerIps.length > 0) {

      // 1. 房主创建房间
      if(resource.playerIps && resource.playerIps.length === 1){
        setIsHost(true);
        setPlayerIp(resource.playerIps[0]);
      }
      // 2. 房主视角加入玩家
      if (isHost && resource.playerIps.length > 1) {
        setPlayerIp(resource.playerIps[0]);
        setOpponentIp(resource.playerIps[1]);
      }

      // 3. 玩家视角加入房间
      if (!isHost && resource.playerIps.length > 1) {
        setPlayerIp(resource.playerIps[1]);
        setOpponentIp(resource.playerIps[0]);
        if (!newPlayerStatus[resource.playerIps[0]]) {
          newPlayerStatus[resource.playerIps[0]] = '未准备';
        }
      }
      // 更新所有玩家的准备状态
      resource.playerIps.forEach(ip => {
        if (resource.playerPanels[ip]) {
          newPlayerStatus[ip] = resource.playerPanels[ip].ready ? '已准备' : '未准备';
        }
      });
      
      // 移除已离开房间的玩家状态
      Object.keys(newPlayerStatus).forEach(ip => {
        if (!resource.playerIps.includes(ip)) {
          delete newPlayerStatus[ip];
        }
      });
    } else {
      // 没有玩家在房间中
      setOpponentIp(null);
      setIsHost(false);
    }
    
    setPlayerStatus(newPlayerStatus);
    
    // 检查是否两个玩家都已准备
    const allPlayers = resource.playerIps;
    if (allPlayers.length === 2) {
      const player1Ready = resource.playerPanels[allPlayers[0]]?.ready || false;
      const player2Ready = resource.playerPanels[allPlayers[1]]?.ready || false;
      setBothReady(player1Ready && player2Ready);
    } else {
      setBothReady(false);
    }
  }

  // 处理房间指令
  function handleRoomCommand(command: any) {
    console.log('收到房间指令:', command);
    
    // 监听START_GAME指令并跳转页面
    if (command === 'START_GAME') {
      // 跳转到loading页面
      Taro.navigateTo({
        url: `/pages/loading/index?roomId=${roomId}&playerIp=${playerIp}`
      });
    }
  }

  // 准备/取消准备
  const toggleReady = () => {
    playerReady(playerIp);
  };

  // 开始游戏
  const startGameClick = () => {
    startGame();
    // 跳转到loading页面
    // Taro.navigateTo({
    //   url: `/pages/loading/index?roomId=${roomId}&playerIp=${playerIp}`
    // });
  };

  // 关闭房间
  const closeRoom = () => {
    // 关闭websocket连接
    disconnectWebSocket();
    sendGameCommand('close_room', {});
    // 返回首页
    Taro.navigateBack();
  };

  return (
    <View className='room-container'>
      <Text className='room-title'>房间号: {roomId}</Text>
      <Text className='player-ip'>玩家IP: {playerIp}</Text>
      
      <View className='players-container'>
        <View className='player-item'>
          <Text className='player-label'>玩家{playerIp} (自己)</Text>
          <Text className='player-status'>{playerStatus[playerIp] || '未连接'}</Text>
        </View>
        
        <View className='player-item'>
          <Text className='player-label'>
            {opponentIp ? `玩家${opponentIp} (对手)` : '等待对手加入...'}
          </Text>
          <Text className='player-status'>
            {opponentIp ? (playerStatus[opponentIp] || '未连接') : '未加入'}
          </Text>
        </View>
      </View>
      
      {!opponentIp && (
        <Text className='waiting-text pulse-animation'>等待其他玩家加入房间...</Text>
      )}
      
      <View className='actions-container'>
        <Button className='action-btn' onClick={toggleReady}>
          {playerStatus[playerIp] === '已准备' ? '取消准备' : '准备'}
        </Button>
        
        {isHost && opponentIp && (
          <Button 
            className={`action-btn ${bothReady ? '' : 'pulse-animation'} start-btn`} 
            onClick={startGameClick}
            disabled={!bothReady}
          >
            开始游戏
          </Button>
        )}
        
        {isHost && (
          <Button className='action-btn close-btn' onClick={closeRoom}>
            关闭房间
          </Button>
        )}

        {!isHost && (
          <Button className='action-btn close-btn' onClick={closeRoom}>
            退出房间
          </Button>
        )}
      </View>
      
      <View className='connection-status'>
        <Text>连接状态: {isConnected ? '已连接' : '未连接'}</Text>
      </View>
    </View>
  );
}